package it.koutifaris.travianmap.communication.mapdownloader;

import it.koutifaris.travianmap.dal.TravianServerService;
import it.koutifaris.travianmap.dal.TravianServerService.TravianServer;
import it.koutifaris.travianmap.mapsqlparser.ProgressHandler;
import android.os.AsyncTask;

public class DownloadMapAsyncService extends AsyncTask<TravianServerService.TravianServer, Long, Void> implements ProgressHandler {

	private final DownloadMapService mapService;
	private DownloadProgressHandler downloadHandler;
	private long totalBytes;
	private Exception error;
	private TravianServer server;

	public DownloadMapAsyncService(DownloadMapService mapService) {
		this.mapService = mapService;
	}

	public void download(TravianServer server, DownloadProgressHandler downloadHandler) {
		this.downloadHandler = downloadHandler;
		this.server = server;
		DownloadProgressHelper.downloadServiceHelper().register(server.getServerId(), downloadHandler);
		this.execute(server);
	}

	@Override
	protected void onPreExecute() {
		downloadHandler.onPreInit();
	}

	@Override
	protected Void doInBackground(TravianServer... servers) {
		try {
			mapService.download(servers[0], this);
		} catch (Exception e) {
			error = e;
			cancel(true);
		}

		return null;
	}

	@Override
	protected void onCancelled() {
		DownloadProgressHelper.downloadServiceHelper().unregister(server.getServerId());
		downloadHandler.onError(error);
	}

	@Override
	protected void onProgressUpdate(Long... values) {
		downloadHandler.onProgress(values[0]);
	}

	@Override
	protected void onPostExecute(Void result) {
		DownloadProgressHelper.downloadServiceHelper().unregister(server.getServerId());
		downloadHandler.onFinish(totalBytes);
	}

	@Override
	public void init(long contentLength) {
		downloadHandler.init(contentLength);
	}

	@Override
	public void onProgress(long byteCount) {
		publishProgress(byteCount);
	}

	@Override
	public void onFinish(long byteCount) {
		totalBytes = byteCount;
	}

}
